package br.com.amadeus.android.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import br.com.amadeus.android.activities.home.R;
import br.com.amadeus.android.adapters.SocialHistoryAdapter;
import br.com.amadeus.android.business.FacadeAmadeusDroid;
import br.com.amadeus.android.entities.Config;
import br.com.amadeus.android.entities.SocialHistory;
import br.com.amadeus.android.util.ConstantsAmadeusDroid;
import br.com.amadeus.android.util.JSONReader;
import br.com.amadeus.android.util.RESTFileContent;

public class ServiceSyncTimelineAmadeus extends Service implements Runnable{
	protected static final String CATEGORIA = "curso";
	protected static final int INSERIR = 0;
	
	@Override
	public void onCreate() {
		new Thread(this).start();
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	public void run() {
				
		Config config = FacadeAmadeusDroid.getInstance(this).getConfig();
		String url = config.getAmadeus_url() + 
        ConstantsAmadeusDroid.HOST_AMADEUS_WEB_HISTORY;
		RESTFileContent rfc = new RESTFileContent();
        InputStream is;
        String historic;
        ArrayList<SocialHistory> listSocial;
		try {
			is = rfc.getRESTFileContent(url);
			historic = rfc.toString(is);
			listSocial = JSONReader.getAmadeusHistoric(historic);
			
			boolean test = FacadeAmadeusDroid.getInstance(this).syncronizeTimeline(listSocial);
			if (test) {
				createNotification();
			}
			
		} catch (ClientProtocolException e1) {
			Log.e(CATEGORIA, e1.getMessage(), e1);
		} catch (IOException e1) {
			Log.e(CATEGORIA, e1.getMessage(), e1);
		} catch (JSONException e) {
			Log.e(CATEGORIA, e.getMessage(), e);
		}
		stopSelf();
	}
	
	/** Handler utilizado para atualizar a view **/
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// o msg.what permite identificar a mensagem
			switch (msg.what) {
			case INSERIR:
				// recebe a mensagem para atualizar a view
				List<SocialHistory> list = FacadeAmadeusDroid.getInstance().getListSocialHistory();
				SocialHistoryAdapter sha = new SocialHistoryAdapter(ServiceSyncTimelineAmadeus.this, list);
				
				LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
				View layout = layoutInflater.inflate(R.layout.amadeus_screen_4, null);
								
				ListView lv = (ListView) layout.findViewById(R.id.lvSocialHistoric);
				lv.setAdapter(sha);
				
				break;
			default:
				break;
			}
		}
	};


	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	private void createNotification() {

		String mensagemBarraStatus = ConstantsAmadeusDroid.TICKER_TEXT_NOTIFICATION;

		CharSequence titulo = ConstantsAmadeusDroid.TITLE_NOTIFICATION;

		String mensagem = ConstantsAmadeusDroid.MESSAGE_NOTIFICATION_TIMELINE;

		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		Intent it = new Intent("HOME");

		PendingIntent p = PendingIntent.getActivity(this, 0, it, 0);

		Notification n = new Notification(R.drawable.amadeus_notification, mensagemBarraStatus, System.currentTimeMillis());

		n.setLatestEventInfo(this, titulo, mensagem, p);

		n.vibrate = new long[] { 100, 250, 100, 500 };

		nm.notify(R.string.app_name, n);

	}
	
	
}
